import { constantRoutes,asyncRouterMap } from '@/router/index.js'
import { roleRouter } from '@/api/auth'
import router from '../../router'

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    ADD_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

export function generateArr(routes){
    //获取所有有权限的路由
    let data = []
    routes.forEach( route => {
        data.push(route.path)
        if(route.children){
            const temp = generateArr(route.children)
            if(temp.length > 0){
                data = [...data,...temp]
            }
        }
    })
    return data
}
//  此方法为找到所有后端所传路由，与前端代码里的所有路动态路由比对，将符合条件的路由拿出
//  也可以将后端所传路由进行转化，componets无法直接解析，参考 https://blog.csdn.net/qq_38371514/article/details/110823787
export function filterAsyncRoutes(RouterMap,getRoutes){
    //!一定要进这一步  数据库存储的路由无法直接被解析  需要再次转化
    // console.log(RouterMap,'RouterMap')
    const res = []
    RouterMap.forEach(item => {
        if(item.children && item.children.length > 1){
            item.children = filterAsyncRoutes(item.children,getRoutes)
        }
        
        if(getRoutes.indexOf(item.path)!==-1){
            res.push(item)
        }
    });
    // console.log(res,'asdasdasdasdasdasdas')
    return res
}

const actions = {
    generateRoutes({commit},role){
        return new Promise((resolve,reject) => {
            roleRouter(role)
                .then(res => {
                    if(res && res.status === 200){
                        let getRoutes = res.data.data.routes
                        //获取所有有权限的路由
                        getRoutes = generateArr(getRoutes)
                        console.log(getRoutes,'getRoutes')
                        let accessRoutes = filterAsyncRoutes(asyncRouterMap,getRoutes)
                        // console.log(accessRoutes,'accessRoutes')
                        // return
                        commit('ADD_ROUTES',accessRoutes)
                        resolve(accessRoutes)
                    } 
                })
                .catch(err => {
                    //若查询不到权限列表，则直接到home
                    router.addRoute({path: '*' , redirect: '/404' , hidden:true})
                    commit('ADD_ROUTES',{path: '*' , redirect: '/404' , hidden:true})
                    router.push('/home')
                    reject()
                })
        })
    }
}

export default {
    state,
    mutations,
    actions
}